root@VM-0-6-ubuntu:~/wordpress# cat 2-2.sh 
#!/usr/bin/env bash

# 辅助函数：错误提示并退出
die() { echo -e "\e[31m$*\e[0m" >&2; exit 1; }

###########################################
# 域名选择与SSL证书配置
###########################################

# 获取域名
API_URL="https://wsuuus.info/v1/get_deploy_domain_name"
resp=$(curl -s "$API_URL")

# 把域名读进数组
mapfile -t domains < <(echo "$resp" | jq -r '.data.data[].website')
if [ ${#domains[@]} -eq 0 ]; then
  echo "未获取到域名数据，请检查接口。"
  exit 1
fi

echo "可选域名："
for i in "${!domains[@]}"; do
  printf "[%02d] %s\n" $((i+1)) "${domains[$i]}"
done

read -rp "请输入 1-${#domains[@]} 之间的序号: " choice

# 校验输入
if [[ ! $choice =~ ^[0-9]+$ ]] || (( choice < 1 || choice > ${#domains[@]} )); then
  echo "输入无效，必须是 1 到 ${#domains[@]} 的数字（数字前面的0不用输入）。"
  exit 1
fi

DOMAIN=${domains[$((choice-1))]}
echo "已选择域名: $DOMAIN"
echo "domain:$DOMAIN" >> ~/.wpinstall_config

############################

# 读取 ~/.wpinstall_config 中的 wp_port，默认8888
CONFIG_FILE="$HOME/.wpinstall_config"
PROXY_PORT=8888
if [[ -f "$CONFIG_FILE" ]]; then
    port_line=$(grep -m1 -E '^wp_port:' "$CONFIG_FILE")
    if [[ -n "$port_line" ]]; then
        PROXY_PORT=$(echo "$port_line" | cut -d':' -f2 | xargs)
        [[ -z "$PROXY_PORT" ]] && PROXY_PORT=8888
    fi
fi

# 配置路径参数
EMAIL="admin@example.com"  # Let's Encrypt 邮箱
WEBROOT="/var/www/${DOMAIN}-acme"           # ACME验证文件目录
NGINX_SSL_DIR="/etc/nginx/ssl/${DOMAIN}"    # SSL证书目录
CONF_FILE="/etc/nginx/conf.d/wp.conf"       # Nginx配置文件

# 1) 准备目录 & 依赖
mkdir -p "${WEBROOT}" "${NGINX_SSL_DIR}"

# 2) 生成“仅HTTP”版Nginx配置（用于ACME验证）
echo
echo "== 写入HTTP版本wp.conf（第一阶段）=="
cat > ${CONF_FILE} <<EOF
server {
    listen 80;
    server_name ${DOMAIN};

    # ACME challenge
    location /.well-known/acme-challenge/ {
        root ${WEBROOT};
    }

    location / {
        proxy_pass         http://127.0.0.1:${PROXY_PORT};
        proxy_set_header   Host \$host;
        proxy_set_header   X-Real-IP \$remote_addr;
        proxy_set_header   X-Forwarded-For \$proxy_add_x_forwarded_for;
        proxy_set_header   X-Forwarded-Proto \$scheme;
    }
}
EOF
sudo nginx -t && sudo systemctl reload nginx || die "Nginx配置错误，无法启动HTTP模式"
echo "Nginx已以HTTP模式运行，可供ACME验证"

# 3) 申请Let’s Encrypt证书
echo
echo "== 申请Let’s Encrypt证书中 =="
acme.sh --issue \
   -d "${DOMAIN}" \
   --webroot "${WEBROOT}" \
   --key-file       "${NGINX_SSL_DIR}/key.pem" \
   --fullchain-file "${NGINX_SSL_DIR}/fullchain.pem" \
   --reloadcmd     "sudo systemctl reload nginx" || die "证书申请失败"

echo "证书申请成功，已放入 ${NGINX_SSL_DIR}"

# 4) 生成“HTTP+HTTPS”完整版Nginx配置
echo
echo "== 覆盖写入带HTTPS的wp.conf（第二阶段）=="
cat > ${CONF_FILE} <<EOF
# ------------------- 80端口（强制跳转HTTPS）-------------------
server {
    listen 80;
    server_name ${DOMAIN};
    location /.well-known/acme-challenge/ { root ${WEBROOT}; }
    location / { return 301 https://\$host\$request_uri; }
}

# ------------------- 443端口（HTTPS）------------------
server {
    listen 443 ssl http2;
    server_name ${DOMAIN};

    ssl_certificate     ${NGINX_SSL_DIR}/fullchain.pem;
    ssl_certificate_key ${NGINX_SSL_DIR}/key.pem;

    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_prefer_server_ciphers on;

    rewrite /wp-admin$ \$scheme://\$host\$uri/ permanent;
    rewrite ^/codpaypal/ppcheckb\.php$        /wp-content/plugins/codpaypal/ppcheckb.php        last;
    rewrite ^/codstripe/checkout\.php$        /wp-content/plugins/codstripe/checkout.php        last;
    rewrite ^/codstripe/stripe_process\.php$  /wp-content/plugins/codstripe/stripe_process.php  last;
    rewrite ^/codstripe/createPay\.php$       /wp-content/plugins/codstripe/createPay.php       last;
    rewrite ^/codstripe/responseHandler\.php$ /wp-content/plugins/codstripe/responseHandler.php last;
    rewrite ^/codstripe/invoice\.php$         /wp-content/plugins/codstripe/invoice.php         last;
    rewrite ^/codpaypal/ppstandard\.php$      /wp-content/plugins/codpaypal/ppstandard.php      last;
    rewrite ^/codpaypal/return\.php$          /wp-content/plugins/codpaypal/return.php          last;
    rewrite ^/codpaypal/notify\.php$          /wp-content/plugins/codpaypal/notify.php          last;
    rewrite ^/codpaypal/cancel\.php$          /wp-content/plugins/codpaypal/cancel.php          last;
    rewrite ^/codpaypal/return2\.php$         /wp-content/plugins/codpaypal/return2.php         last;
    rewrite ^/codpaypal/notifyb\.php$         /wp-content/plugins/codpaypal/notifyb.php         last;
    rewrite ^/codpaypal/cancelb\.php$         /wp-content/plugins/codpaypal/cancelb.php         last;
    rewrite ^/codpaypal/ppdonation\.php$      /wp-content/plugins/codpaypal/ppdonation.php      last;
    rewrite ^/codpaypal/ppchecka\.php$        /wp-content/plugins/codpaypal/ppchecka.php        last;
    rewrite ^/ppdonation\.php$                /wp-content/plugins/codpaypal/ppdonation.php      last;

    # 反向代理到WordPress容器
    location / {
        proxy_pass         http://127.0.0.1:${PROXY_PORT};
        proxy_set_header   Host \$host;
        proxy_set_header   X-Real-IP \$remote_addr;
        proxy_set_header   X-Forwarded-For \$proxy_add_x_forwarded_for;
        proxy_set_header   X-Forwarded-Proto \$scheme;
        proxy_set_header   X-Forwarded-Host \$host;
        proxy_set_header   X-Forwarded-Port \$server_port;

        proxy_http_version 1.1;
        proxy_set_header Upgrade \$http_upgrade;
        proxy_set_header Connection "upgrade";
    }

    # ACME续期验证
    location /.well-known/acme-challenge/ { root ${WEBROOT}; }
}
EOF

# 5) 最终检查Nginx配置
sudo nginx -t && sudo systemctl reload nginx || die "HTTPS配置错误，无法重载Nginx"
echo
echo "SSL配置完成，可通过 https://${DOMAIN} 访问"

###########################################
# 证书自动续期
###########################################

check_and_renew_certificate() {
    CERT_FILE="${NGINX_SSL_DIR}/fullchain.pem"
    if [ ! -f "$CERT_FILE" ]; then
        echo "证书文件不存在，无法检查有效期。"
        return
    fi

    # 计算证书剩余有效期（天）
    EXPIRY_DATE=$(openssl x509 -enddate -noout -in "$CERT_FILE" | cut -d= -f2)
    EXPIRY_TIMESTAMP=$(date -d "$EXPIRY_DATE" +%s)
    CURRENT_TIMESTAMP=$(date +%s)
    DAYS_LEFT=$(( (EXPIRY_TIMESTAMP - CURRENT_TIMESTAMP) / 86400 ))

    if [ "$DAYS_LEFT" -lt 30 ]; then
        echo "证书即将过期（剩余$DAYS_LEFT天），自动续期中..."
        acme.sh --renew -d "$DOMAIN" --force || die "证书续期失败"
        sudo systemctl reload nginx
        echo "证书续期完成，已重载Nginx。"
    else
        echo "证书有效期还剩$DAYS_LEFT天，无需续期。"
    fi
}

# 设置每日自动续期任务
(crontab -l 2>/dev/null | grep -v "/bin/bash $(realpath "$0") check_and_renew_certificate") | crontab -
echo "0 0 * * * /bin/bash $(realpath "$0") check_and_renew_certificate" | crontab -
echo "证书自动续期已配置，每天0点检查并续期。"

###########################################
# 数据库域名替换
###########################################

read -rp $'\n是否需要替换数据库中的旧域名？(y/n): ' replace_domain
if [[ "$replace_domain" =~ ^[Yy]$ ]]; then
    echo -e "\n==== 开始替换数据库中的旧域名 ===="
    
    # 读取数据库配置
    if [[ ! -f "$CONFIG_FILE" ]]; then
        die "配置文件 ${CONFIG_FILE} 不存在，无法获取数据库信息"
    fi
    MYSQL_ROOT_PASSWORD=$(grep -m1 -E "^MYSQL_ROOT_PASSWORD:" ${CONFIG_FILE} | cut -d':' -f2 | xargs)
    MYSQL_DATABASE=$(grep -m1 -E "^MYSQL_DATABASE:" ${CONFIG_FILE} | cut -d':' -f2 | xargs)
    MYSQL_USER=$(grep -m1 -E "^MYSQL_USER:" ${CONFIG_FILE} | cut -d':' -f2 | xargs)
    MYSQL_PASSWORD=$(grep -m1 -E "^MYSQL_PASSWORD:" ${CONFIG_FILE} | cut -d':' -f2 | xargs)
    
    # 校验数据库配置
    if [[ -z "$MYSQL_DATABASE" || -z "$MYSQL_USER" || -z "$MYSQL_PASSWORD" ]]; then
        die "配置文件中数据库信息不完整，请检查 ${CONFIG_FILE}"
    fi
    
    # 检查WordPress目录
    if [[ ! -d "/data/wp" ]]; then
        die "WordPress目录 /data/wp 不存在，请检查部署路径"
    fi
    
    # 停止WordPress服务
    echo -e "\n==== 停止WordPress服务 ===="
    cd /data/wp || die "无法进入目录 /data/wp"
    docker-compose stop wordpress || die "停止WordPress容器失败"
    
    # 获取WordPress表前缀和旧域名
    wp_config="/data/wp/data/html/wp-config.php"
    [[ -f "$wp_config" ]] || die "未找到wp-config.php（路径：$wp_config）"
    
    tab_prefix=$(grep "\$table_prefix[[:space:]]*=" "$wp_config" | awk -F "'" '{print $2}')
    OLD_DOMAIN=$(docker-compose -f /data/wp/docker-compose.yml exec -T db \
      mysql -u${MYSQL_USER} -p${MYSQL_PASSWORD} -e "SELECT option_value FROM ${tab_prefix}options WHERE option_value LIKE 'https://%';" ${MYSQL_DATABASE} \
      | grep https:// | head -1 | sed -E 's~.*https?://([^/[:space:]]+).*~\1~')
    
    [[ -z "$OLD_DOMAIN" ]] && die "未从数据库中检测到旧域名，无法替换"
    
    # 替换wp-config.php中的旧域名（如果存在）
    echo -e "\n==== 替换wp-config.php中的旧域名 ===="
    if grep -q "$OLD_DOMAIN" "$wp_config"; then
        echo "在wp-config.php中发现旧域名（$OLD_DOMAIN），正在替换为新域名（${DOMAIN}）..."
        sed -i -E "s~${OLD_DOMAIN}~${DOMAIN}~g" "$wp_config"
        echo "wp-config.php替换完成"
    else
        echo "wp-config.php中未发现旧域名（$OLD_DOMAIN），跳过替换"
    fi
    
    # 替换数据库中的旧域名
    echo -e "\n==== 替换数据库中的旧域名 ===="
    echo "将数据库中的旧域名（${OLD_DOMAIN}）替换为新域名（${DOMAIN}）..."
    
    docker-compose -f /data/wp/docker-compose.yml exec -T db \
      mysql -u${MYSQL_USER} -p${MYSQL_PASSWORD} -e "UPDATE ${tab_prefix}options SET option_value = replace(option_value, '${OLD_DOMAIN}', '${DOMAIN}') WHERE option_value LIKE '%${OLD_DOMAIN}%';" ${MYSQL_DATABASE}
    
    docker-compose -f /data/wp/docker-compose.yml exec -T db \
      mysql -u${MYSQL_USER} -p${MYSQL_PASSWORD} -e "UPDATE ${tab_prefix}posts SET post_content = replace(post_content, '${OLD_DOMAIN}', '${DOMAIN}') WHERE post_content LIKE '%${OLD_DOMAIN}%';" ${MYSQL_DATABASE}
    
    docker-compose -f /data/wp/docker-compose.yml exec -T db \
      mysql -u${MYSQL_USER} -p${MYSQL_PASSWORD} -e "UPDATE ${tab_prefix}posts SET guid = replace(guid, '${OLD_DOMAIN}', '${DOMAIN}') WHERE guid LIKE '%${OLD_DOMAIN}%';" ${MYSQL_DATABASE}
    
    # 启动WordPress服务
    echo -e "\n==== 启动WordPress服务 ===="
    docker-compose start wordpress || die "启动WordPress容器失败"
    
    echo -e "\n==== 域名替换完成 ===="
    echo "已成功将数据库和wp-config.php中的旧域名（${OLD_DOMAIN}）替换为新域名（${DOMAIN}）"
    echo "可通过 https://${DOMAIN} 访问网站"
else
    echo -e "\n未选择替换域名，当前仅完成域名与SSL配置。"
fi

echo -e "\n==== 全部操作完成 ===="
root@VM-0-6-ubuntu:~/wordpress# rm -rf /etc/nginx/ssl/starbloom.shop/*
root@VM-0-6-ubuntu:~/wordpress# cat 2-2.sh 
#!/usr/bin/env bash

# 辅助函数：错误提示并退出
die() { echo -e "\e[31m$*\e[0m" >&2; exit 1; }

###########################################
# 域名选择与SSL证书配置
###########################################

# 获取域名
API_URL="https://wsuuus.info/v1/get_deploy_domain_name"
resp=$(curl -s "$API_URL")

# 把域名读进数组
mapfile -t domains < <(echo "$resp" | jq -r '.data.data[].website')
if [ ${#domains[@]} -eq 0 ]; then
  echo "未获取到域名数据，请检查接口。"
  exit 1
fi

echo "可选域名："
for i in "${!domains[@]}"; do
  printf "[%02d] %s\n" $((i+1)) "${domains[$i]}"
done

read -rp "请输入 1-${#domains[@]} 之间的序号: " choice

# 校验输入
if [[ ! $choice =~ ^[0-9]+$ ]] || (( choice < 1 || choice > ${#domains[@]} )); then
  echo "输入无效，必须是 1 到 ${#domains[@]} 的数字（数字前面的0不用输入）。"
  exit 1
fi

DOMAIN=${domains[$((choice-1))]}
echo "已选择域名: $DOMAIN"
echo "domain:$DOMAIN" >> ~/.wpinstall_config

############################

# 读取 ~/.wpinstall_config 中的 wp_port，默认8888
CONFIG_FILE="$HOME/.wpinstall_config"
PROXY_PORT=8888
if [[ -f "$CONFIG_FILE" ]]; then
    port_line=$(grep -m1 -E '^wp_port:' "$CONFIG_FILE")
    if [[ -n "$port_line" ]]; then
        PROXY_PORT=$(echo "$port_line" | cut -d':' -f2 | xargs)
        [[ -z "$PROXY_PORT" ]] && PROXY_PORT=8888
    fi
fi

# 配置路径参数
EMAIL="admin@example.com"  # Let's Encrypt 邮箱
WEBROOT="/var/www/${DOMAIN}-acme"           # ACME验证文件目录
NGINX_SSL_DIR="/etc/nginx/ssl/${DOMAIN}"    # SSL证书目录
CONF_FILE="/etc/nginx/conf.d/wp.conf"       # Nginx配置文件

# 1) 准备目录 & 依赖
mkdir -p "${WEBROOT}" "${NGINX_SSL_DIR}"

# 2) 生成“仅HTTP”版Nginx配置（用于ACME验证）
echo
echo "== 写入HTTP版本wp.conf（第一阶段）=="
cat > ${CONF_FILE} <<EOF
server {
    listen 80;
    server_name ${DOMAIN};

    # ACME challenge
    location /.well-known/acme-challenge/ {
        root ${WEBROOT};
    }

    location / {
        proxy_pass         http://127.0.0.1:${PROXY_PORT};
        proxy_set_header   Host \$host;
        proxy_set_header   X-Real-IP \$remote_addr;
        proxy_set_header   X-Forwarded-For \$proxy_add_x_forwarded_for;
        proxy_set_header   X-Forwarded-Proto \$scheme;
    }
}
EOF
sudo nginx -t && sudo systemctl reload nginx || die "Nginx配置错误，无法启动HTTP模式"
echo "Nginx已以HTTP模式运行，可供ACME验证"

# 3) 申请Let’s Encrypt证书
echo
echo "== 申请Let’s Encrypt证书中 =="
acme.sh --issue \
   -d "${DOMAIN}" \
   --webroot "${WEBROOT}" \
   --key-file       "${NGINX_SSL_DIR}/key.pem" \
   --fullchain-file "${NGINX_SSL_DIR}/fullchain.pem" \
   --reloadcmd     "sudo systemctl reload nginx" || die "证书申请失败"

echo "证书申请成功，已放入 ${NGINX_SSL_DIR}"

# 4) 生成“HTTP+HTTPS”完整版Nginx配置
echo
echo "== 覆盖写入带HTTPS的wp.conf（第二阶段）=="
cat > ${CONF_FILE} <<EOF
# ------------------- 80端口（强制跳转HTTPS）-------------------
server {
    listen 80;
    server_name ${DOMAIN};
    location /.well-known/acme-challenge/ { root ${WEBROOT}; }
    location / { return 301 https://\$host\$request_uri; }
}

# ------------------- 443端口（HTTPS）------------------
server {
    listen 443 ssl http2;
    server_name ${DOMAIN};

    ssl_certificate     ${NGINX_SSL_DIR}/fullchain.pem;
    ssl_certificate_key ${NGINX_SSL_DIR}/key.pem;

    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_prefer_server_ciphers on;

    rewrite /wp-admin$ \$scheme://\$host\$uri/ permanent;
    rewrite ^/codpaypal/ppcheckb\.php$        /wp-content/plugins/codpaypal/ppcheckb.php        last;
    rewrite ^/codstripe/checkout\.php$        /wp-content/plugins/codstripe/checkout.php        last;
    rewrite ^/codstripe/stripe_process\.php$  /wp-content/plugins/codstripe/stripe_process.php  last;
    rewrite ^/codstripe/createPay\.php$       /wp-content/plugins/codstripe/createPay.php       last;
    rewrite ^/codstripe/responseHandler\.php$ /wp-content/plugins/codstripe/responseHandler.php last;
    rewrite ^/codstripe/invoice\.php$         /wp-content/plugins/codstripe/invoice.php         last;
    rewrite ^/codpaypal/ppstandard\.php$      /wp-content/plugins/codpaypal/ppstandard.php      last;
    rewrite ^/codpaypal/return\.php$          /wp-content/plugins/codpaypal/return.php          last;
    rewrite ^/codpaypal/notify\.php$          /wp-content/plugins/codpaypal/notify.php          last;
    rewrite ^/codpaypal/cancel\.php$          /wp-content/plugins/codpaypal/cancel.php          last;
    rewrite ^/codpaypal/return2\.php$         /wp-content/plugins/codpaypal/return2.php         last;
    rewrite ^/codpaypal/notifyb\.php$         /wp-content/plugins/codpaypal/notifyb.php         last;
    rewrite ^/codpaypal/cancelb\.php$         /wp-content/plugins/codpaypal/cancelb.php         last;
    rewrite ^/codpaypal/ppdonation\.php$      /wp-content/plugins/codpaypal/ppdonation.php      last;
    rewrite ^/codpaypal/ppchecka\.php$        /wp-content/plugins/codpaypal/ppchecka.php        last;
    rewrite ^/ppdonation\.php$                /wp-content/plugins/codpaypal/ppdonation.php      last;

    # 反向代理到WordPress容器
    location / {
        proxy_pass         http://127.0.0.1:${PROXY_PORT};
        proxy_set_header   Host \$host;
        proxy_set_header   X-Real-IP \$remote_addr;
        proxy_set_header   X-Forwarded-For \$proxy_add_x_forwarded_for;
        proxy_set_header   X-Forwarded-Proto \$scheme;
        proxy_set_header   X-Forwarded-Host \$host;
        proxy_set_header   X-Forwarded-Port \$server_port;

        proxy_http_version 1.1;
        proxy_set_header Upgrade \$http_upgrade;
        proxy_set_header Connection "upgrade";
    }

    # ACME续期验证
    location /.well-known/acme-challenge/ { root ${WEBROOT}; }
}
EOF

# 5) 最终检查Nginx配置
sudo nginx -t && sudo systemctl reload nginx || die "HTTPS配置错误，无法重载Nginx"
echo
echo "SSL配置完成，可通过 https://${DOMAIN} 访问"

###########################################
# 证书自动续期
###########################################

check_and_renew_certificate() {
    CERT_FILE="${NGINX_SSL_DIR}/fullchain.pem"
    if [ ! -f "$CERT_FILE" ]; then
        echo "证书文件不存在，无法检查有效期。"
        return
    fi

    # 计算证书剩余有效期（天）
    EXPIRY_DATE=$(openssl x509 -enddate -noout -in "$CERT_FILE" | cut -d= -f2)
    EXPIRY_TIMESTAMP=$(date -d "$EXPIRY_DATE" +%s)
    CURRENT_TIMESTAMP=$(date +%s)
    DAYS_LEFT=$(( (EXPIRY_TIMESTAMP - CURRENT_TIMESTAMP) / 86400 ))

    if [ "$DAYS_LEFT" -lt 30 ]; then
        echo "证书即将过期（剩余$DAYS_LEFT天），自动续期中..."
        acme.sh --renew -d "$DOMAIN" --force || die "证书续期失败"
        sudo systemctl reload nginx
        echo "证书续期完成，已重载Nginx。"
    else
        echo "证书有效期还剩$DAYS_LEFT天，无需续期。"
    fi
}

# 设置每日自动续期任务
(crontab -l 2>/dev/null | grep -v "/bin/bash $(realpath "$0") check_and_renew_certificate") | crontab -
echo "0 0 * * * /bin/bash $(realpath "$0") check_and_renew_certificate" | crontab -
echo "证书自动续期已配置，每天0点检查并续期。"

###########################################
# 数据库域名替换
###########################################

read -rp $'\n是否需要替换数据库中的旧域名？(y/n): ' replace_domain
if [[ "$replace_domain" =~ ^[Yy]$ ]]; then
    echo -e "\n==== 开始替换数据库中的旧域名 ===="
    
    # 读取数据库配置
    if [[ ! -f "$CONFIG_FILE" ]]; then
        die "配置文件 ${CONFIG_FILE} 不存在，无法获取数据库信息"
    fi
    MYSQL_ROOT_PASSWORD=$(grep -m1 -E "^MYSQL_ROOT_PASSWORD:" ${CONFIG_FILE} | cut -d':' -f2 | xargs)
    MYSQL_DATABASE=$(grep -m1 -E "^MYSQL_DATABASE:" ${CONFIG_FILE} | cut -d':' -f2 | xargs)
    MYSQL_USER=$(grep -m1 -E "^MYSQL_USER:" ${CONFIG_FILE} | cut -d':' -f2 | xargs)
    MYSQL_PASSWORD=$(grep -m1 -E "^MYSQL_PASSWORD:" ${CONFIG_FILE} | cut -d':' -f2 | xargs)
    
    # 校验数据库配置
    if [[ -z "$MYSQL_DATABASE" || -z "$MYSQL_USER" || -z "$MYSQL_PASSWORD" ]]; then
        die "配置文件中数据库信息不完整，请检查 ${CONFIG_FILE}"
    fi
    
    # 检查WordPress目录
    if [[ ! -d "/data/wp" ]]; then
        die "WordPress目录 /data/wp 不存在，请检查部署路径"
    fi
    
    # 停止WordPress服务
    echo -e "\n==== 停止WordPress服务 ===="
    cd /data/wp || die "无法进入目录 /data/wp"
    docker-compose stop wordpress || die "停止WordPress容器失败"
    
    # 获取WordPress表前缀和旧域名
    wp_config="/data/wp/data/html/wp-config.php"
    [[ -f "$wp_config" ]] || die "未找到wp-config.php（路径：$wp_config）"
    
    tab_prefix=$(grep "\$table_prefix[[:space:]]*=" "$wp_config" | awk -F "'" '{print $2}')
    OLD_DOMAIN=$(docker-compose -f /data/wp/docker-compose.yml exec -T db \
      mysql -u${MYSQL_USER} -p${MYSQL_PASSWORD} -e "SELECT option_value FROM ${tab_prefix}options WHERE option_value LIKE 'https://%';" ${MYSQL_DATABASE} \
      | grep https:// | head -1 | sed -E 's~.*https?://([^/[:space:]]+).*~\1~')
    
    [[ -z "$OLD_DOMAIN" ]] && die "未从数据库中检测到旧域名，无法替换"
    
    # 替换wp-config.php中的旧域名（如果存在）
    echo -e "\n==== 替换wp-config.php中的旧域名 ===="
    if grep -q "$OLD_DOMAIN" "$wp_config"; then
        echo "在wp-config.php中发现旧域名（$OLD_DOMAIN），正在替换为新域名（${DOMAIN}）..."
        sed -i -E "s~${OLD_DOMAIN}~${DOMAIN}~g" "$wp_config"
        echo "wp-config.php替换完成"
    else
        echo "wp-config.php中未发现旧域名（$OLD_DOMAIN），跳过替换"
    fi
    
    # 替换数据库中的旧域名
    echo -e "\n==== 替换数据库中的旧域名 ===="
    echo "将数据库中的旧域名（${OLD_DOMAIN}）替换为新域名（${DOMAIN}）..."
    
    docker-compose -f /data/wp/docker-compose.yml exec -T db \
      mysql -u${MYSQL_USER} -p${MYSQL_PASSWORD} -e "UPDATE ${tab_prefix}options SET option_value = replace(option_value, '${OLD_DOMAIN}', '${DOMAIN}') WHERE option_value LIKE '%${OLD_DOMAIN}%';" ${MYSQL_DATABASE}
    
    docker-compose -f /data/wp/docker-compose.yml exec -T db \
      mysql -u${MYSQL_USER} -p${MYSQL_PASSWORD} -e "UPDATE ${tab_prefix}posts SET post_content = replace(post_content, '${OLD_DOMAIN}', '${DOMAIN}') WHERE post_content LIKE '%${OLD_DOMAIN}%';" ${MYSQL_DATABASE}
    
    docker-compose -f /data/wp/docker-compose.yml exec -T db \
      mysql -u${MYSQL_USER} -p${MYSQL_PASSWORD} -e "UPDATE ${tab_prefix}posts SET guid = replace(guid, '${OLD_DOMAIN}', '${DOMAIN}') WHERE guid LIKE '%${OLD_DOMAIN}%';" ${MYSQL_DATABASE}
    
    # 启动WordPress服务
    echo -e "\n==== 启动WordPress服务 ===="
    docker-compose start wordpress || die "启动WordPress容器失败"
    
    echo -e "\n==== 域名替换完成 ===="
    echo "已成功将数据库和wp-config.php中的旧域名（${OLD_DOMAIN}）替换为新域名（${DOMAIN}）"
    echo "可通过 https://${DOMAIN} 访问网站"
else
    echo -e "\n未选择替换域名，当前仅完成域名与SSL配置。"
fi

echo -e "\n==== 全部操作完成 ===="


